import React, { Component } from "react";
import QueueAnim from "rc-queue-anim";
import { Table, message, Button, Input, Popconfirm } from "antd";
import AllContent from "@/components/DetailTabs/AllContent";
import { getNewestDrafList, getContentDetails, getDetailesStatisticalData, delNewArtile } from "../../services/services";
import "./NewestDraft.less";
import SearchBar from "../../components/SearchContent/SearchBar";
import moment from "moment";
import { judgeMonCode, handleMonTextForNewsList } from '@/utils/formatMonTextStyle.js'

class NewestDraft extends Component {
  constructor(props) {
    super(props);
    this.state = {
      per_page: 10, //表格数据当前页显示条数
      total: 0, //表格数据总条数
      page: 1, //表格数据当前页码
      keyword: "", //搜索关键词
      site_name: "", //站点名称
      loading: false, //表格加载效果
      tableData: [], //表格数据
      showDetailVariable: true, //显示详情页变量
      tabKey: "1", //详情tab页索引
      article_ids: [], //文章id数组
      currentRow: null, //当前行的数据
      statisticalData: [], //统计数据
      selectedRowKeys: [],
      start_time: "",
      end_time: ""
    };
  }
  componentDidMount() {
    this.getTableData();
  }
  // 搜索
  handleSeachButton = () => {
    this.setState(
      {
        page: 1,
        loading: true
      },
      () => {
        const { keyword, page, per_page, start_time, end_time } = this.state;
        const params = {
          keyword,
          page,
          per_page,
          start_time,
          end_time
        };
        this.getTableData(params);
      }
    );
  };
  // 获取表格数据
  getTableData = (params = {}) => {
    getNewestDrafList(params)
      .then(res => {
        if (res.code === 200) {
          const result = res.data;
          this.setState({
            loading: false,
            total: result.total,
            tableData: result.data
          });
        } else {
          this.setState({
            loading: false
          });
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 获取详情数据
  getDetailsData = row => {
    console.log(row);
    const params = {
      site_id: row.site_id,
      content_type: row.content_type,
      content_id: row.content_id
    };
    getContentDetails(params)
      .then(res => {
        if (res.code === 200) {
          this.setState({
            detailsContent: res.data || {}
          });
        } else if (res.code === 500) {
          console.log(res.msg);
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 表格显示条数切换
  pageSizeChange = (current, size) => {
    this.setState(
      {
        per_page: size,
        page: current,
        loading: true
      },
      () => {
        const { keyword, page, per_page, start_time, end_time } = this.state;
        const params = {
          keyword,
          page,
          per_page,
          start_time,
          end_time
        };
        this.getTableData(params);
      }
    );
  };
  // 当前页面变化
  currentPageChange = (page, pageSize) => {
    this.setState(
      {
        page,
        loading: true
      },
      () => {
        const { keyword, page, per_page, start_time, end_time } = this.state;
        const params = {
          keyword,
          page,
          per_page,
          start_time,
          end_time
        };
        this.getTableData(params);
      }
    );
  };
  // 跳转至详情
  showDetailChange = row => {
    this.setState(
      {
        showDetailVariable: false
      },
      () => {
        this.getDetailsData(row);
        this.getStatistical(row);
      }
    );
  };
  // 表格数据多选框的变化
  onTableSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRowKeys
    });
  };
  // 返回上一级
  goBack = () => {
    this.setState(
      {
        showDetailVariable: true
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 获取详情统计数据
  getStatistical = row => {
    const params = {
      site_id: row.site_id,
      content_id: row.content_id,
      content_type: row.content_type,
      source: 1
    };
    getDetailesStatisticalData(params)
      .then(res => {
        if (res.code === 200) {
          let sdata = [];
          let arr = ["阅读量", "评论量", "点赞量", "分享量"];
          let arr1 = ["scan_count", "comment_count", "like_count", "share_count"];
          for (let i = 0; i < 4; i++) {
            let obj = {};
            obj["x"] = arr[i];
            obj["y"] = res.data[arr1[i]];
            sdata.push(obj);
          }
          this.setState({
            statisticalData: sdata
          });
        } else if (res.code === 500) {
          console.log(res.msg);
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 输入框变化
  inputChange = e => {
    this.setState({
      keyword: e.target.value
    });
  };
  // 点击重置
  handleReset = () => {
    this.setState(
      {
        page: 1,
        keyword: "",
        selectedRowKeys: [],
        loading: true,
        start_time: "",
        end_time: ""
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 删除
  handleConfirm = () => {
    if (!this.state.selectedRowKeys.length) {
      return message.error("请选择需要删除的选项");
    }
    delNewArtile({ ids: this.state.selectedRowKeys })
      .then(res => {
        if (res.code) {
          this.setState({
            selectedRowKeys: [],
            loading: true
          });
          this.getTableData({ page: this.state.page, keyword: this.state.keyword, start_time: this.state.start_time, end_time: this.state.end_time });
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  handleTimeChange = data => {
    const start_time = moment(data.start_time).format("YYYY-MM-DD HH:mm:ss");
    const end_time = moment(data.end_time).format("YYYY-MM-DD HH:mm:ss");
    this.setState({
      start_time,
      end_time
    });
    console.log(start_time, end_time, "---------------------");
  };
  render() {
    const { tableData, total, loading, keyword, selectedRowKeys } = this.state;
    const columns = [
      {
        title: "标题",
        dataIndex: "title",
        // key: "title",
        align: "center",
        width: "40%",
        render: (text, record, index) => (
          <div style={{ textAlign: "left" }}>
            {/* 判断是否符合蒙文编码 */}
            { judgeMonCode(text) ?
              handleMonTextForNewsList(tableData[index].create_time, text)
            :
            <div style={{ textAlign: "center" }}> {text} </div> 
            }
          </div>
        )
      },
      {
        title: "类型",
        dataIndex: "content_type",
        key: "content_type",
        align: "center",
        render: (text, record) => {
          if (text === 1) {
            return "文章";
          } else if (text === 2) {
            return "图集";
          } else if (text === 4) {
            return "视频";
          }
        }
      },
      {
        title: "发布站点",
        dataIndex: "site_name",
        key: "site_name",
        align: "center"
      },
      {
        title: "发布人",
        dataIndex: "create_user",
        key: "create_user",
        align: "center"
      },
      {
        title: "推送时间",
        dataIndex: "create_time",
        key: "create_time",
        align: "center"
      },
      {
        title: "操作",
        key: "is_delete",
        align: "center",
        render: (text, record) => {
          return (
            <span style={{ cursor: "pointer", color: "#1890ff" }} onClick={this.showDetailChange.bind(this, record)}>
              查看详情
            </span>
          );
        }
      }
    ];
    // 表格分页器配置项
    const paginationProps = {
      current: this.state.page,
      showSizeChanger: true,
      showQuickJumper: true,
      total: total,
      showTotal: () => `共 ${this.state.total} 条记录`,
      pageSize: this.state.per_page,
      pageSizeOptions: ["5", "10", "20", "50"],
      onChange: this.currentPageChange,
      onShowSizeChange: this.pageSizeChange
    };
    // 表格选择
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onTableSelectChange
    };
    return (
      <QueueAnim className="NewestDraft">
        <div key="t2" className="BasicContent">
          <div className="main">
            {this.state.showDetailVariable ? (
              <div>
                <div className="action">
                  <SearchBar setSpread={this.handleTimeChange} data={{ start_t: this.state.start_time, end_t: this.state.end_time }}></SearchBar>
                  <Input className="searchInput" value={keyword} type="text" placeholder="请输入关键词" onChange={this.inputChange} />
                  <Button className="searchBtn" type="primary" onClick={this.handleSeachButton}>
                    搜索
                  </Button>
                  <Button onClick={this.handleReset}>重置</Button>
                  <Popconfirm title="确认删除选中项吗？" okText="确定" onConfirm={this.handleConfirm} cancelText="取消">
                    <Button className="allDelete" type="danger">
                      批量删除
                    </Button>
                  </Popconfirm>
                </div>
                <Table rowSelection={rowSelection} loading={loading} rowKey={recored => recored.id} columns={columns} dataSource={tableData} bordered pagination={paginationProps} />
              </div>
            ) : (
              <div>
                {this.state.detailsContent ? (
                  <AllContent
                    statisticalData={this.state.statisticalData}
                    siteId={this.state.site_id}
                    refresh={this.handleDel}
                    categoryId={this.state.categoryId}
                    parentBack={this.goBack}
                    contentData={this.state.detailsContent}
                    tabKey={this.state.tabKey}
                  />
                ) : null}
              </div>
            )}
          </div>
        </div>
      </QueueAnim>
    );
  }
}

export default NewestDraft;
